<?php

namespace app\common\model;

use think\Model;
use think\Db; // Added missing import for Db

/**
 * 用户公考资源模型
 */
class UserCivil extends Model
{
    // 表名
    protected $name = 'user_civil';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;


    /**
     * 获取到期时间文本
     */
    public function getEndTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['end_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    /**
     * 设置到期时间
     */
    protected function setEndTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    /**
     * 判断是否过期
     */
    public function getIsExpiredAttr($value, $data)
    {
        $end_time = $data['end_time'] ?? 0;
        return $end_time > 0 && $end_time < time();
    }

    /**
     * 检查用户是否有有效的公考资源
     * @param int $user_id 用户ID
     * @return array|false
     */
    public static function checkUserValidCivil($user_id)
    {
        $current_time = time();

        return self::where('user_id', $user_id)
            ->where('end_time', '>', $current_time)  // 未过期的资源
            ->where('teacher_id', '>', 0)  // 有老师分配的
            ->where('civil_id', '>', 0)    // 有公考资源的
            ->find();
    }

    /**
     * 获取用户所有有效的公考资源
     * @param int $user_id 用户ID
     * @return \think\Collection
     */
    public static function getUserValidCivils($user_id)
    {
        $current_time = time();
        return self::where('user_id', $user_id)
            ->where('end_time', '>', $current_time)  // 未过期的资源
            ->where('teacher_id', '>', 0)  // 有老师分配的
            ->where('civil_id', '>', 0)    // 有公考资源的
            ->select();
    }

    /**
     * 获取用户公考资源详细信息（包含关联数据）
     * @param int $user_id 用户ID
     * @return array
     */
    public static function getUserCivilList($user_id)
    {
        $current_time = time();
        // 使用JOIN查询获取详细信息
        $result = self::alias('uc')
            ->join('civil c', 'uc.civil_id = c.id', 'LEFT')  // 假设有civil表
            ->join('user u', 'uc.teacher_id = u.id', 'LEFT')  // 假设老师信息在admin表
            ->field('uc.*, c.title as civil_name, c.label as civil_label,c.image as civil_image, u.nickname as teacher_name')
            ->where('uc.user_id', $user_id)
            ->where('uc.end_time', '>', $current_time)
            ->where('uc.teacher_id', '>', 0)
            ->where('uc.civil_id', '>', 0)
            ->paginate()
            ->each(function ($item, $key) {
                if ($item['civil_label']) {
                    $item['civil_label'] = explode(',', $item['civil_label']);
                } else {
                    $item['civil_label'] = [];
                }
            });
        return $result ?: [];
    }

    /**公考详情 */
    public static function getUserCivilDetails($id)
    {
        $current_time = time();
        // 使用JOIN查询获取详细信息
        $result = self::alias('uc')
            ->join('civil c', 'uc.civil_id = c.id', 'LEFT')  // 假设有civil表
            ->field('uc.*, c.title as civil_name, c.label as civil_label,c.image as civil_image,c.course_code as civil_course_code')
            ->where('uc.id', $id)
            ->where('uc.end_time', '>', $current_time)
            ->where('uc.teacher_id', '>', 0)
            ->where('uc.civil_id', '>', 0)
            ->find();
        if ($result) {
            if ($result['civil_label']) {
                $result['civil_label'] = explode(',', $result['civil_label']);
            } else {
                $item['civil_label'] = [];
            }
        }
        return $result;
    }




    /**
     * 获取老师的所有学生列表（根据user_id去重）
     * @param int $teacher_id 老师ID
     * @return array
     */
    public static function getTeacherStudents($teacher_id)
    {
        try {
            // 查询老师的所有学生，根据user_id去重
            $students = self::alias('uc')
                ->join('user u', 'uc.user_id = u.id', 'LEFT')  // 关联用户表获取学生信息
                ->field('uc.user_id, u.nickname, u.avatar, u.mobile, u.email, u.createtime as user_createtime')
                ->where('uc.teacher_id', $teacher_id)
                ->where('uc.user_id', '>', 0)  // 确保有学生ID
                ->group('uc.user_id')  // 根据user_id去重
                ->order('uc.createtime DESC')  // 按创建时间倒序
                ->select();
            
            if ($students) {
                // 为每个学生获取公考资源统计信息
                foreach ($students as &$student) {
                    // 获取该学生的公考资源数量
                    $civil_count = self::where('teacher_id', $teacher_id)
                        ->where('user_id', $student['user_id'])
                        ->count();
                    
                    // 获取该学生的有效公考资源数量（未过期）
                    $valid_civil_count = self::where('teacher_id', $teacher_id)
                        ->where('user_id', $student['user_id'])
                        ->where('end_time', '>', time())
                        ->count();
                    
                    // 获取该学生的即将过期的公考资源数量（7天内过期）
                    $expiring_count = self::where('teacher_id', $teacher_id)
                        ->where('user_id', $student['user_id'])
                        ->where('end_time', '>', time())
                        ->where('end_time', '<=', time() + 7 * 24 * 3600)
                        ->count();
                    
                    $student['civil_count'] = $civil_count;           // 总公考资源数
                    $student['valid_civil_count'] = $valid_civil_count; // 有效公考资源数
                    $student['expiring_count'] = $expiring_count;     // 即将过期的资源数
                    $student['user_createtime_text'] = date('Y-m-d H:i:s', $student['user_createtime']);
                }
            }
            return $students ?: [];
        } catch (\Exception $e) {
            return [];
        }
    }

    /**
     * 获取学生的详细公考资源列表
     * @param int $teacher_id 老师ID
     * @param int $user_id 学生ID
     * @return array
     */
    public static function getStudentCivilDetails($teacher_id, $user_id)
    {
        try {
            $current_time = time();
            $result = self::alias('uc')
                ->join('civil c', 'uc.civil_id = c.id', 'LEFT')  // 关联公考表
                ->field('uc.*, c.title as civil_name, c.label as civil_label, c.image as civil_image')
                ->where('uc.teacher_id', $teacher_id)
                ->where('uc.user_id', $user_id)
                ->where('uc.civil_id', '>', 0)
                ->order('uc.createtime DESC')
                ->select();
            if ($result) {
                foreach ($result as &$item) {
                    if ($item['civil_label']) {
                        $item['civil_label'] = explode(',', $item['civil_label']);
                    } else {
                        $item['civil_label'] = [];
                    }
                    // 添加状态信息
                    $item['is_expired'] = $item['end_time'] < $current_time;
                    $item['days_left'] = $item['end_time'] > $current_time ? 
                        ceil(($item['end_time'] - $current_time) / (24 * 3600)) : 0;
                    $item['end_time_text'] = date('Y-m-d H:i:s', $item['end_time']);
                    $item['createtime_text'] = date('Y-m-d H:i:s', $item['createtime']);
                }
            }
            return $result ?: [];
            
        } catch (\Exception $e) {
            return [];
        }
    }
    
}
